package com.lss.studydemo;

import java.util.ArrayList;
import java.util.List;

// 被观察者
public class TemperatureMonitor {
    // 温度监听器列表
    private List<TemperatureListener> temperatureListeners = new ArrayList<>();
     float targetTemperature = 30.0f;
     float currentTemperature = 25.0f;

    public void addTemperatureListener(TemperatureListener listener) {
        if (temperatureListeners != null && !temperatureListeners.contains(listener)) {
            temperatureListeners.add(listener);
        }
    }

    public void removeTemperatureListener(TemperatureListener listener) {
        if (temperatureListeners != null && temperatureListeners.contains(listener)) {
            temperatureListeners.remove(listener);
        }
    }

    // 通知所有监听器温度超过阈值
    private void notifyTemperatureExceeded(TemperatureEvent event) {
        for (TemperatureListener listener : temperatureListeners) {
            listener.onTemperatureExceeded(event);
        }
    }

    // 通知所有监听器温度达到阈值
    private void notifyTemperatureReached(TemperatureEvent event) {
        for (TemperatureListener listener : temperatureListeners) {
            listener.onTemperatureReached(event);
        }
    }

    // 移除所有监听
    public void clearTemperatureListeners() {
        temperatureListeners.clear();
    }

    // 更新温度
    public void updateTemperature(float newTemperature) {
        float oldTemperature = currentTemperature;
        currentTemperature = newTemperature;

        // 创建温度事件对象
        TemperatureEvent event = new TemperatureEvent(newTemperature, targetTemperature);

        // 检查温度是否超过阈值
        checkTemperatureState(oldTemperature, event);
    }

    private void checkTemperatureState(float oldTemperature, TemperatureEvent event) {
        // 只有当温度越过阈值时才触发
        if (event.isExceeded() && oldTemperature <= targetTemperature) {
            notifyTemperatureExceeded(event);
        }
        // 当温度达到阈值但之前超过时触发
        else if (!event.isExceeded() && oldTemperature > targetTemperature) {
            notifyTemperatureReached(event);
        }
    }

    public void setTargetThreshold(float threshold) {
        targetTemperature = threshold;
    }
}
